<template>
  <div class="Record">
    <div class="Record_rocd">
      <div>看学历视频课程 轻松得学分</div>
      <div>集满学分自动兑换本科学历</div>
    </div>

    <!-- 进度条 -->
    <div class="progress flex-space-center">
      <van-circle
        class="circle"
        v-model="currentRate"
        :rate="0"
        layer-color=" #232323"
        :stroke-width="120"
        :text="circleText"
        color="#FEA300"
        size="200px"
        :speed="120"
      />

      <!-- 显示已完成学分 -->
      <div class="credits flex-space-center">
        <div class="creditsItems credits_one flex-space-center">
          <p></p>已完成学分
        </div>
        <div class="creditsItems credits_two flex-space-center">
          <p></p>未完成学分
        </div>
      </div>
<!--      荣誉证书图片-->
      <div v-if="currentRate*1>=100" class="certificate" style="margin-right:0.4rem;">
        <img :src="certificateUrl" alt />
        <van-button type="primary" color="#000" text="点击查看" @click="show = true" />
      </div>
    </div>

    <van-overlay :show="show" @click.stop="show = false">
      <div class="wrapper" :show="show1">
        <img :src="certificateUrl" alt />
        <div class="block">
          <div v-for="(item,index) in activeList" :key="index" @click.stop="getCert(item)">
            <img :src="item.images" alt="">
            <div>{{item.name}}</div>
          </div>
        </div>
      </div>
    </van-overlay>
  </div>
</template>

<script>
  import {GETUSERCERT, GETTOKEN, UPDATECERT} from "../../../apis/oldUniversity";
  import * as qiniu from "qiniu-js";
  export default {
    name: "",
    data() {
      return {
        activeList: [
          {
            images:require("@/components/common/img/bendi.png" ),
            name: "下载到本地"
          },
          // {
          //   images:require("@/components/common/img/weixin.png" ),
          //   name: "分享至微信"
          // },
          // {
          //   images:require("@/components/common/img/pengyouquan.png" ),
          //   name: "分享到朋友圈"
          // },
          {
            images:require("@/components/common/img/youji.png" ),
            name: "邮寄给我"
          }
        ],
        currentRate:0,//进度条初始值
        show: false,
        show1: true,
        userCertMsg:{},//用户证书详情
        certificateUrl:'',//证书地址
      };
    },
    props: {},
    components: {},
    mounted() {

    },
    methods: {
      // 获取证书的方式
      getCert(item){
        if(item.name=="邮寄给我"){
          // is_post 0 未寄送 1已寄送
          if(this.userCertMsg.is_post*1==0){
            this.$router.push("sendMsg")
          }else{
            this.$toast("已寄送给您了！")
          }
        }else if(item.name == '下载到本地'){
          if(this.certificateUrl){
            this.downloadCert()
          }

        }
      },
      // 下载证书
      downloadCert(){
        if (this.systemInfo()==='android'){
          window.android.saveFile("IMAGE",this.certificateUrl);
        }else if(this.systemInfo()==='ios') {
          window.webkit.messageHandlers.saveFile.postMessage("IMAGE",this.certificateUrl);
        }
      },
      // 绘制有名字的证书
      drawPhoto(){
        let canvas=document.createElement("canvas");    //创建canvas
        canvas.width = 286;
        canvas.height = 202;
        let context=canvas.getContext('2d');        //创建画布
        let img=new Image();               //因为拿不到图片静态资源，所以创建图片标签
        img.setAttribute("crossOrigin",'anonymous');       //解决图片跨域问题,也要放到赋值前，否贼大部分浏览器会报错
        img.src = this.userCertMsg.url;//证书背景图
        //加载图片
        img.onload=()=>{
          //绘制图片
          context.drawImage(img,0,0,286,202);
          //字体大小
          context.font="12px Arial";
          //字体填充颜色
          context.fillStyle="red";
          //字体文字，显示位置
          // 姓名
          context.fillText(this.userCertMsg.name,20,90);
          // 时间
          const startTime = String(this.userCertMsg.start_at).split('-')
          context.fillText(startTime[0],50,110);
          context.fillText(startTime[1],80,110);
          context.fillText(startTime[2],104,110);
          const endTime = String(this.userCertMsg.end_at).split('-')
          context.fillText(startTime[1],124,110);
          context.fillText(startTime[2],144,110);
          // 学习内容
          context.fillText(this.userCertMsg.desc,40,124);

          //合成图片
          let certificateUrl = canvas.toDataURL('image/png');
          // this.certificateUrl = certificateUrl;
          this.dataURLtoBlob(certificateUrl,'image/jpeg')
        }
      },
      //-------------------------- 接口开始 --------------------
      // 证书详情
      getUserCert(){
        let getUserCert = GETUSERCERT
        getUserCert().then( res => {
          if(res.data.code*1===200){
            this.userCertMsg = res.data.data;
            // 学过的百分数
            this.currentRate = parseInt((this.userCertMsg.now_credit*1/this.userCertMsg.total_credit*1)*100)>=0?parseInt((this.userCertMsg.now_credit*1/this.userCertMsg.total_credit*1)*100):0
            // is_update 0 没有更新过证书 1 更新过
            if(this.currentRate*1>=100 && this.userCertMsg.is_update*1==0){
              // 绘制新证书
              this.drawPhoto()
            }

          } else {
            this.$toast(res.data.message);
          }
        }).catch(error => {
          console.log(error)
        })
      },
      //将base64格式图片转换为文件形式
      dataURLtoBlob(dataurl,type) {
        var arr = dataurl.split(','), mime = arr[0].match(/:(.*?);/)[1],
          bstr = atob(arr[1]), n = bstr.length, u8arr = new Uint8Array(n);
        while(n--){
          u8arr[n] = bstr.charCodeAt(n);
        }
        var fileData =  new Blob([u8arr], {type:type})
        let fileOfBlob = new File([fileData],new Date().getTime() + '.jpg');//重命名
        this.uploadImg(fileOfBlob)
      },
      // 上传图片
      uploadImg (form) {
        // console.log(e);
        let that = this;
        let file = form;
        var  uploadInit ;
        let getToken = GETTOKEN
        getToken()
          .then(res => {
            // console.log(res)
            if(res.data.code*1==200) {
              uploadInit=res.data.data;
              if (uploadInit=="") { return; }
              this.uploadDomain ="http://up-z1.qiniup.com/";
              let key = new Date().getTime() + file.name;
              let config = {
                chunkSize: 8,
                region: qiniu.region.z1,
                domain: this.uploadDomain
              };
              var putExtra = {

                ...config,
              }
              // console.log(qiniu);

              let observable = qiniu.upload(file, key, uploadInit, putExtra, config);
              let subscription = observable.subscribe({
                next(res){
                  let process = res.total.percent;
                  that.process = Math.floor(process);
                },
                error(err){
                  Toast.fail("上传失败：" + err.message);
                },
                complete(res){
                  // 证书链接
                  that.certificateUrl="http://oss.dayinyun.com/"+res.key;
                  // 更新证书信息
                  // that.upDataCert()
                }
              });
            }
          })
      },
      // 更新证书
      upDataCert(){
        let upDataCert = UPDATECERT
        let params = {
          cert_url:this.certificateUrl,//证书链接
        }
        upDataCert().then( res => {
          if(res.data.code*1===200){

          } else {
            // this.$toast(res.data.message);
          }
        }).catch(error => {
          console.log(error)
        })
      },

    },
    computed:{
      // 圆圈进度条的文案
      circleText(){
        return '已学' + this.currentRate.toFixed(0) + '%';
      }
    }
  };
</script>

<style lang='less' scoped>
@import (reference) url(../../../assets/less/common);
.Record {
  width: 4.3rem;
  height: 0.86rem;
  // border: 1px solid #fff;
  margin: 0.34rem auto;
}
.Record .Record_rocd {
  font-size: @fontSize34;
  font-weight: @fontWeight500;
  font-family: @fontFamily500;
  color:@whiteColor;
}

.Record .Record_rocd div:nth-of-type(2) {
  font-size: @fontSize30;
  margin-left: 0.4rem;
  margin-top: 0.05rem;
}
.progress {
  flex-direction: column;
  padding-top: 0.8rem;
  box-sizing: border-box;
}
.progress .credits {
  margin-top: 0.5rem;
  flex-direction: column;

  .creditsItems{
    font-size: @fontSize30;
    font-weight: @fontWeight400;
    font-family: @fontFamily500;
    color:#ffffff;
    margin-bottom:0.34rem;
    p{
      width:0.56rem;
      height:0.3rem;
      border-radius:0.05rem;
      margin-right:0.2rem;
    }
  }
  .credits_one{
    p{
      background:#FEA300;
    }
  }
  .credits_two{
    p{
      background:#232323;
    }
  }
}

.wrapper {
  display: flex;
  align-items: center;
  justify-content: center;
  height: 100%;
  position: relative;
}
.wrapper img {
  width: 5.72rem;
  height: 4.02rem;
}

.block {
  width: 100%;
  height: 2.9rem;
  // border: 1px solid #fff;
  position: absolute;
  bottom: 0;
  display: flex;
  justify-content: space-around;
  align-items: center;
  // line-height: 1.5rem;
}
.block div{
  width: 1.7rem;
  height: 1.5rem;
  // border: 1px solid #fff;
  display: flex;
  flex-direction: column;
  text-align: center;
  font-size: @fontSize28;
  font-weight: @fontWeight400;
  font-family: @fontFamily400;
  color:@whiteColor;
  margin-top: 0.13rem;
}
.block div img{
  width: 0.8rem;
  height: 0.8rem;
  margin: 0 auto;
}
.certificate{
  position: relative;
}
.certificate img {
  width: 5.72rem;
  height: auto;
  margin: 0.8rem 0 0 0.6rem;
}
/deep/ .certificate .van-button--normal .van-button__content{
  color: #fff;
  font-size: 0.33rem;
  position: absolute;
  bottom:0.84rem;
  left:0.56rem;
  right:0.56rem;
  width:5.8rem;
  height:0.86rem;
  opacity: 0.5;
  background: #000;
  text-align: center;
  /*padding:0 0.7rem 0.7rem 0;*/
}
/deep/ .van-overlay{
  z-index: 200;
}
  /deep/.van-circle__text{
    color:#ffffff;
    font-size: @fontSize38;
    font-weight: @fontWeight400;
    font-family: @fontFamily500;
  }

</style>
